package com.taomu.app.zongchouhuli.moudle.login.contract.impl;

import android.text.TextUtils;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.taomu.app.zongchouhuli.R;
import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.entity.BaseResponse;
import com.taomu.app.zongchouhuli.http.api.BaseResponseCode;
import com.taomu.app.zongchouhuli.http.api.HttpObserver;
import com.taomu.app.zongchouhuli.http.api.Request;
import com.taomu.app.zongchouhuli.http.res.ResArticleEntity;
import com.taomu.app.zongchouhuli.http.res.ResUserInfoEntity;
import com.taomu.app.zongchouhuli.http.utls.RxSchedulerHelper;
import com.taomu.app.zongchouhuli.moudle.login.contract.LoginContract;
import com.taomu.app.zongchouhuli.utils.ParseUtil;
import com.taomu.app.zongchouhuli.utils.StorageHelper;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function3;
import io.reactivex.schedulers.Schedulers;

public class LoginPresenter implements LoginContract.Presenter {

    private LoginContract.View mContractView;

    private CompositeDisposable disposable;

    public LoginPresenter(LoginContract.View mContractView){
        this.mContractView = mContractView;
        this.disposable = new CompositeDisposable();
    }

    @Override
    public void login(String phone, String password) {
        Request.getIntence().login(phone,password)
                .flatMap(new Function<String, Observable<BaseChangeResponse<ResUserInfoEntity>>>() {
                    @Override
                    public  Observable<BaseChangeResponse<ResUserInfoEntity>> apply(String json) throws Exception {
                        BaseResponse<JSONObject> baseResponse = ParseUtil.parseObject(json,BaseResponse.class);
                        BaseChangeResponse<ResUserInfoEntity> data = new BaseChangeResponse<>();
                        data.setData(ParseUtil.parseObject(baseResponse.getData().toString(),ResUserInfoEntity.class));
                        data.setCount(baseResponse.getCount());
                        return Observable.just(data);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseChangeResponse<ResUserInfoEntity>>(mContractView,disposable,true) {
                    @Override
                    public void onNext(BaseChangeResponse<ResUserInfoEntity> baseResponse) {
                        if(mContractView != null){
                            Log.d("dwqdwqdqd", "token:"+baseResponse.getData().getToken());
                            StorageHelper.saveToken(baseResponse.getData().getToken());
                            StorageHelper.saveAccountInfo(ParseUtil.toJson(baseResponse.getData()));
                            StorageHelper.saveUid(String.valueOf(baseResponse.getData().getId()));
                            mContractView.setLogin();
                        }
                    }
                });


    }

    @Override
    public void isSubmitCanClick(TextView tv1, TextView tv2, CheckBox checkBox) {
        Observable.combineLatest(isEditTextInputTextObservable(tv1),
                isEditTextInputTextObservable(tv2),
                getCheckProtocal(),
                new Function3<Boolean, Boolean, Boolean, Boolean>() {
                    @Override
                    public Boolean apply(Boolean aBoolean, Boolean aBoolean2, Boolean aBoolean3) throws Exception {
                        return aBoolean&&aBoolean2&&aBoolean3;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(mContractView != null){
                            if(aBoolean){
                                mContractView.setSubmitCanClick(R.color.base_blue,true);
                            }else{
                                mContractView.setSubmitCanClick(R.color.text_normal_gary,false);
                            }

                        }
                    }
                });
        setCheckEvent(checkBox);

    }

    @Override
    public void getProtocal() {
        Request.getIntence().getArticleInfo(String.valueOf(4))
                .compose(RxSchedulerHelper.<ResArticleEntity>transMain())
                .subscribe(new HttpObserver<ResArticleEntity>(mContractView, disposable, true) {
                    @Override
                    public void onNext(ResArticleEntity baseResponse) {
                        if (mContractView != null) {
                            mContractView.setArticleInfo(baseResponse.getData().getArt_content_html());
                        }
                    }
                });
    }

    private Observable<Boolean> isEditTextInputTextObservable(TextView tv) {
        return RxTextView.afterTextChangeEvents(tv)
                .map(new Function<TextViewAfterTextChangeEvent, Boolean>() {
                    @Override
                    public Boolean apply(TextViewAfterTextChangeEvent event) throws Exception {
                        return !TextUtils.isEmpty(event.view().getText());
                    }
                });
    }

    private ObservableEmitter<Boolean> observableEmitterProtocal;

    private Observable<Boolean> getCheckProtocal() {
        return Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> observableEmitter) throws Exception {
                observableEmitterProtocal = observableEmitter;
                observableEmitterProtocal.onNext(true);
            }
        });
    }

    private void setCheckEvent(CheckBox checkEvent){
        checkEvent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                observableEmitterProtocal.onNext(isChecked);
            }
        });
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onDetch() {
        mContractView = null;
        if(disposable != null){
            disposable.dispose();
            disposable = null;
        }
    }
}
